package com.guomw.report.service.service.impl;

import com.guomw.report.service.models.FileView;
import com.guomw.report.service.models.PageView;
import com.guomw.report.service.service.ConfigService;
import com.guomw.report.service.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private ConfigService configService;

    @Override
    public PageView<FileView> searchList(String folder, String name, int pageIndex) {
        PageView<FileView> pageView = new PageView<>();
        int pageSize = 20;
        File d = new File(configService.getReportFileFolder() + "/" + folder);
        List<FileView> viewList = new ArrayList<>();
        for (File file : d.listFiles()) {
            if (StringUtils.isEmpty(name) || file.getName().startsWith(name)) {
                FileView fileView = new FileView();
                fileView.setName(file.getName());
                fileView.setSize(file.length() / 1024);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(file.lastModified());
                fileView.setTime(sdf.format(cal.getTime()));
                viewList.add(fileView);
            }
        }

        int pageCount = 1;
        pageCount = viewList.size() / pageSize + (viewList.size() % pageSize > 0 ? 1 : 0);
        List<FileView> list = new ArrayList<>();
        for (int i = (pageIndex - 1) * pageSize; i < pageIndex * pageSize; i++) {
            if (i < viewList.size()) list.add(viewList.get(i));
        }
        pageView.setPageCount(pageCount);
        pageView.setTotalCount(Long.parseLong(String.valueOf(viewList.size())));
        pageView.setList(list);
        return pageView;
    }

    @Override
    public void delete(String folder, String name) {
        File file = new File(configService.getReportFileFolder() + "/" + folder + "/" + name);
        if (file.exists()) {
            file.delete();
        }
    }
}
